<?php
declare (strict_types = 1);
// +----------------------------------------------------------------------
// | 页面管理
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\common\model\Article;
use think\facade\View;

class PageController extends AdminBaseController
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $request = $this->request->param();
            $field = $param['field'] ?? 'id';
            $order = $param['order'] ?? 'desc';
            $where[] = ['type', '=', 1];
            if (!empty($request['keywords'])) {
                $where[] = ['title', 'like', $request['keywords']];
            }

            $list = Article::with([
                'user' => function($query) {
                    $query->field('id,nickname');
                }])
                ->where($where)
                ->order($field, $order)
                ->paginate(10);
            return $this->result($list->items(), '', ['count' => $list->total()]);
        }
        return View::fetch('app/content/page');
    }

    public function create()
    {
        View::assign([
            'article'    => null
        ]);
        return View::fetch('app/content/pageform');
    }

    public function save()
    {
        $data = $this->request->param();
        $data['user_id'] = $this->user_id;
        $data['type'] = 1;
        $article = Article::create($data);
        return $this->success('添加成功', $article);
    }

    public function edit($id)
    {
        View::assign([
            'article'    => Article::find($id)
        ]);
        return View::fetch('app/content/pageform');
    }

    public function update($id)
    {
        $param = $this->request->param();
        $param['user_id'] = $this->user_id;
        $article = Article::find($id);
        $result = $article->save($param);
        if (!$result) {
            return $this->error('保存失败');
        }
        return $this->success('保存成功', $article);
    }

    public function delete($id)
    {
        $result = Article::destroy($id);
        if ($result) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
}